package com.eralink.unionuhfreader.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.brightek.thermallibrary.PrinterManager.WHPrinterManager;
import com.eralink.unionuhfreader.MyApplication;
import com.eralink.unionuhfreader.R;
import com.eralink.unionuhfreader.base.BaseActivity;
import com.eralink.unionuhfreader.bean.AppConfirmOrderReqVO;
import com.eralink.unionuhfreader.bean.AppMemberUserInfoRespVO;
import com.eralink.unionuhfreader.bean.CateProduct;
import com.eralink.unionuhfreader.bean.MessageEvent;
import com.eralink.unionuhfreader.bean.PayOrderPayTypeEnum;
import com.eralink.unionuhfreader.bean.ProductOrderDo;
import com.eralink.unionuhfreader.bean.ProductVo;
import com.eralink.unionuhfreader.http.Api;
import com.eralink.unionuhfreader.http.JsonCallBack;
import com.eralink.unionuhfreader.http.Result;
import com.eralink.unionuhfreader.netty.OneCardListen;
import com.eralink.unionuhfreader.util.ByteUtil;
import com.eralink.unionuhfreader.util.SharedPreferencesUtil;
import com.eralink.unionuhfreader.util.ToastUtil;
import com.eralink.unionuhfreader.widget.keybord.KeyboardUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.List;

/**
 * 人工收银台
 */
public class ManualSettlePlateformActivity extends BaseActivity {
    List<CateProduct> cateProducts;
    ProductOrderDo productOrderDo;

    private TextView tx_orderid,tx_amount,tv_found,tx_member_info;
    private EditText ed_real_money;
    private RadioGroup rdg_paytype;
    private RadioButton xianjin;
    private LinearLayout ly_xj,ly_scan,ly_bank,ly_member;
    private Button btn_confirm_order,btn_cancel_order,btn_contine,btn_search_member,btn_clear_member;
    private String payType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manual_settle);
        //先取消上次订单
        //MyApplication.getInstance().cancelPaydata();
        initview();
        String p=getIntent().getBundleExtra("p").getString("products");
        cateProducts= JSON.parseArray(p, CateProduct.class);
        productOrderDo = (ProductOrderDo) getIntent().getBundleExtra("p").getSerializable("productorder");
        tx_orderid.setText("订单ID："+productOrderDo.getId());
        tx_amount.setText("订单金额:"+productOrderDo.getRealTotalAmount());
        xianjin.setChecked(true);
        MyApplication.getInstance().setOneCardListen(oneCardListen);
        sendData(productOrderDo.getRealTotalAmount());
    }
    private void sendData(BigDecimal actmoney) {
        if (!MyApplication.connect_oncard) {
            return;
        }
        int sn = (int) SharedPreferencesUtil.getData(this, "sn", -1);
        if (sn == 65535) {
            sn = 0;
        } else {
            sn = sn + 1;
        }
        //5A 00 01 01 A2 00 04 00 00 00 04 A2
        byte[] data = new byte[10];
        //包序号
        String hexString = Integer.toHexString(sn);
        int datalen = 4 - hexString.length();
        for (int i = 0; i < datalen; i++) {
            hexString = "0" + hexString;
        }
        //byte[] data={0x00, 0x01,0x01, (byte) 0xA2, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04};
        byte[] byteArray = ByteUtil.hexStr2bytes(hexString);
        data[0] = byteArray[0];
        data[1] = byteArray[1];//包序号
        data[2] = (byte) 0x01;//命令类别
        data[3] = (byte) 0xA2;//命令码
        data[4] = (byte) 0x00;
        data[5] = (byte) 0x04;

        //金额数组
        String moneystr = Integer.toHexString(actmoney.multiply(new BigDecimal(100)).intValue());//元转分
        int moneylen = 8 - moneystr.length();
        for (int i = 0; i < moneylen; i++) {
            moneystr = "0" + moneystr;
        }
        byte[] moneyArray = ByteUtil.hexStr2bytes(moneystr);
        data[6] = moneyArray[0];
        data[7] = moneyArray[1];
        data[8] = moneyArray[2];
        data[9] = moneyArray[3];
        byte LRC = ByteUtil.calculateLRC(data);

        byte[] sendata = new byte[12];
        sendata[0] = (byte) 0x5A;
        for (int i = 1; i < 11; i++) {
            sendata[i] = data[i - 1];
        }
        sendata[11] = LRC;
        MyApplication.getInstance().sendData(sendata);
        Log.i("ykj520", "发送数据序列号:" + ByteUtil.bytes2HexStr(sendata));
        SharedPreferencesUtil.saveData(this, "sn", sn);
    }
    private void initview() {
        tx_orderid=findViewById(R.id. tx_orderid);
        tx_amount=findViewById(R.id. tx_amount);
        tv_found=findViewById(R.id.tv_found);
        ed_real_money=findViewById(R.id.ed_real_money);
        ly_xj=findViewById(R.id.ly_xj);
        ly_scan=findViewById(R.id.ly_scan);
        xianjin=findViewById(R.id.xianjin);
        ly_bank=findViewById(R.id.ly_bank);
        ly_member=findViewById(R.id.ly_member);
        tx_member_info=findViewById(R.id.tx_member_info);
        ed_real_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence!=null&& !charSequence.toString().equals("")){
                    String moneystr=charSequence.toString();
                    BigDecimal b=new BigDecimal(moneystr);
                    tv_found.setText("找零:"+b.subtract(productOrderDo.getRealTotalAmount()).toString());
                }else{
                    tv_found.setText("找零:0");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        rdg_paytype=findViewById(R.id.rdg_paytype);
        rdg_paytype.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.xianjin:
                        ly_xj.setVisibility(View.VISIBLE);
                        ly_scan.setVisibility(View.GONE);
                        ly_bank.setVisibility(View.GONE);
                        ly_member.setVisibility(View.GONE);
                        payType= PayOrderPayTypeEnum.CashPayment.getCode();
                        break;
                    case R.id.rb_wxAanalipai:
                        ly_xj.setVisibility(View.GONE);
                        ly_scan.setVisibility(View.VISIBLE);
                        ly_bank.setVisibility(View.GONE);
                        ly_member.setVisibility(View.GONE);
                        payType="BtoC";
                        break;
                    case R.id.unionpay:
                        ly_xj.setVisibility(View.GONE);
                        ly_scan.setVisibility(View.VISIBLE);
                        ly_bank.setVisibility(View.GONE);
                        ly_member.setVisibility(View.GONE);
                        payType=PayOrderPayTypeEnum.UnionPay.getCode();
                        break;
                    case R.id.member_car:
                        ly_xj.setVisibility(View.GONE);
                        ly_scan.setVisibility(View.GONE);
                        ly_bank.setVisibility(View.GONE);
                        ly_member.setVisibility(View.VISIBLE);
                        payType=PayOrderPayTypeEnum.MemberCardPay.getCode();
                        break;
                    case  R.id.bank:
                        ly_xj.setVisibility(View.GONE);
                        ly_scan.setVisibility(View.GONE);
                        ly_bank.setVisibility(View.VISIBLE);
                        ly_member.setVisibility(View.GONE);
                        payType=PayOrderPayTypeEnum.IcCardPay.getCode();
                    break;
                }
            }
        });
        btn_confirm_order=findViewById(R.id.btn_confirm_order);
        btn_cancel_order=findViewById(R.id.btn_cancel_order);
        btn_contine=findViewById(R.id.btn_contine);
        btn_clear_member=findViewById(R.id.btn_clear_member);
   /*  final KeyboardUtil keyboardUtil = new KeyboardUtil(ManualSettlePlateformActivity.this,findViewById(R.id.keyboard_view));
        keyboardUtil.setOnOkClick(new KeyboardUtil.OnOkClick() {
            @Override
            public void onOkClick() {

            }
        });

        ed_real_money.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                keyboardUtil.attachTo(ed_real_money);
                return false;
            }
        });*/
        btn_confirm_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (payType.equals(PayOrderPayTypeEnum.CashPayment.getCode())){
                    //现金支付
                    gotopay("0",PayOrderPayTypeEnum.CashPayment.getCode());
                }else if (payType.equals(PayOrderPayTypeEnum.IcCardPay.getCode())){
                    //刷卡支付
                    gotopay("0",PayOrderPayTypeEnum.CashPayment.getCode());
                }else if (payType.equals(PayOrderPayTypeEnum.MemberCardPay.getCode())){
                    //刷卡支付
                    if (MyApplication.memberUserInfoRespVO==null||MyApplication.memberUserInfoRespVO.getMobile()==null){
                        ToastUtil.showToast("会员信息不存在，请扫描会员二维码");
                        return;
                    }
                    gotopay(MyApplication.memberUserInfoRespVO.getMobile(),PayOrderPayTypeEnum.CashPayment.getCode());
                }

            }
        });
        btn_cancel_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MessageEvent messageEvent=new MessageEvent();
                messageEvent.setType(0);
                EventBus.getDefault().post(messageEvent);
                finish();
            }
        });
        btn_contine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MessageEvent messageEvent=new MessageEvent();
                messageEvent.setType(1);
                EventBus.getDefault().post(messageEvent);
            }
        });
        btn_search_member=findViewById(R.id.btn_search_member);

        btn_search_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showvipdialog();
            }
        });
        btn_clear_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyApplication.memberUserInfoRespVO=null;
                tx_member_info.setText("");
            }
        });
    }

    private void showvipdialog() {
        new XPopup.Builder(this).asInputConfirm("会员手机号", "请输入会员手机号。",
                        new OnInputConfirmListener() {
                            @Override
                            public void onConfirm(String text) {
                               getvip(text);
                            }
                        })
                .show();
    }

    private void getvip(String mobile) {
        Api.getmemberinfo(mobile,new JsonCallBack<Result<AppMemberUserInfoRespVO>>(){
            @Override
            public void onSuccess(Response<Result<AppMemberUserInfoRespVO>> response) {
                Result<AppMemberUserInfoRespVO> appMemberUserInfoRespVOResult=response.body();
                if (appMemberUserInfoRespVOResult.isSucess()){
                    MyApplication.memberUserInfoRespVO=appMemberUserInfoRespVOResult.getData();
                    tx_member_info.setText("会员手机号:"+ MyApplication.memberUserInfoRespVO.getMobile());
                }else {
                    showToast(appMemberUserInfoRespVOResult.getMsg());
                }
            }
        });
    }

    /********************监听扫码***********************/
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int action = event.getAction();
        switch (action) {
            case KeyEvent.ACTION_DOWN:
                if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
                    return super.dispatchKeyEvent(event);
                }
                if (payType.equals(PayOrderPayTypeEnum.CashPayment.getCode())){
                    //现金模式
                    return super.dispatchKeyEvent(event);
                }
                int unicodeChar = event.getUnicodeChar();
                sb.append((char) unicodeChar);
                Log.e("MainActivity", "dispatchKeyEvent: " + unicodeChar + " " + event.getKeyCode() + " scancode=" + event.getScanCode());
                len++;
                startScan();
                return true;
            default:
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    private Handler myHandler = new Handler();
    int oldLen = 0;
    boolean isScaning = false;
    private StringBuilder sb = new StringBuilder();
    int len = 0;
    private void startScan() {
        if (isScaning) {
            return;
        }
        isScaning = true;
        timerScanCal();
    }

    private void timerScanCal() {
        oldLen = len;
        myHandler.postDelayed(scan, 100);
    }

    Runnable scan = new Runnable() {
        @Override
        public void run() {
            if (oldLen != len) {
                timerScanCal();
                return;
            }
            isScaning = false;
            if (sb.length() > 0) {
                excCode(sb.toString());
                sb.setLength(0);
            }
        }
    };

    private void excCode(String code) {
        if (isPhoneNumber(code)){
            //扫地会员码
            return;
        }
        if (payType.equals("BtoC")){
            //微信支付宝直连扫码付
            gotopay(code,"WxBToC");
        }else{
            gotopay(code,payType);
        }

       // payType
    }

    private void gotopay(String code,String paytype) {
        int indexN=code.indexOf("\n");
        if (indexN>=0){
            code=code.substring(0,indexN);
        }
        code=code.replaceAll("[\r\n]+","").replaceAll("\\D", "");
        AppConfirmOrderReqVO appConfirmOrderReqVO=new AppConfirmOrderReqVO();
        appConfirmOrderReqVO.setOrderId(productOrderDo.getId());
        appConfirmOrderReqVO.setPayCode(code);
        appConfirmOrderReqVO.setPayType(paytype);
        Api.confirmOrder(appConfirmOrderReqVO,new JsonCallBack<Result>(){
            @Override
            public void onSuccess(Response<Result> response) {
                Result result=response.body();
                if (result!=null&&result.isSucess()){
                    ToastUtil.showToast("支付成功");
                    MessageEvent messageEvent=new MessageEvent();
                    messageEvent.setType(2);
                    messageEvent.setData(paytype);
                    EventBus.getDefault().post(messageEvent);
                    //打印机打印
                    finish();
                }else{
                    showToast(result.getMsg());
                }
            }
        });
    }
    /*钱箱*/

    public static boolean isPhoneNumber(String number) {
        // 正则表达式匹配，手机号的格式可以根据需求进行修改
        String regex = "^(13\\d|14[5-9]|15[0-3,5-9]|16[6]|17[0-8]|18\\d|19[0-3,5-9])\\d{8}$";
        return number.matches(regex);
    }
    String paymobile;
    /*一卡通数据*/
    OneCardListen oneCardListen = new OneCardListen() {
        @Override
        public void payCallBack(String cardNo, long payAmount, String sn) {
            while (cardNo.startsWith("0")) {
                cardNo = cardNo.substring(1, cardNo.length());
            }
            gotopay(cardNo,"onecard");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().cancelPaydata();
    }
}
